<template>
    <div class="templateO">
        <div class="templateO-title">
            <span>模块权限</span>
            <div class="templateO-btn" style="float: right">
                <div @click="handleCheckAllEmpty" style="cursor:pointer;"><img src="../../../assets/images/empty.png" alt="" title="清空"></div>
                <div @click="handleCheckAllChange" style="cursor:pointer;"><img src="../../../assets/images/checkAll.png" alt="" title="全选"></div>
                <div @click="setCheckedKeys" style="cursor:pointer;"><img src="../../../assets/images/closed.png" alt="" title="合拢"></div>
                <div @click="setCheckedNodes" style="cursor:pointer;"><img src="../../../assets/images/an.png" alt="" title="展开"></div>
            </div>
        </div>
        <el-scrollbar style="height: calc(100% - 40px);">
            <el-tree :data="templeteTreeData" :default-expand-all="defaultExpand" ref="templeteTreeRef" node-key="id" show-checkbox :accordion="false" :props="templleteProps" :highlight-current="true" :default-checked-keys="checkedKeys"></el-tree>
        </el-scrollbar>
        <div class="saveBtn">
            <el-button type="primary" class="operatorBtn" @click="saveTempleteData">保存</el-button>
        </div>
    </div>
</template>
<script>
/**
 * 授权---模块权限
 * zqf
 */
export default {
    data() {
        return {
            templeteTreeData: [],
            templleteProps: {
                children: 'submenuList',
                label: 'name'
            },
            defaultExpand:true,                     //默认展开所有节点
            checkedId:[],                           //勾选到的id
            halfCheckedId:[],                       //模块权限半选中的id
            systemId: this.$store.state.systemId,
            userId: this.$store.state.userManagementStore.userId,
            checkedKeys: [],
            arr:[],                                 //存放所有树节点的id，用于全选函数
        }
    },
    methods:{
        handleCheckAllChange(val){                              //模块权限的全选
            this.$refs.templeteTreeRef.setCheckedKeys(this.arr);
            this.checkedId = this.arr;
        },
        handleCheckAllEmpty(){                                  //模块权限的清空
            this.$refs.templeteTreeRef.setCheckedKeys([]);
            this.checkedId = [];
        },
        setCheckedKeys() {                                      //模快权限的合拢事件
            this.defaultExpand=false;
            for(var i=0;i<this.$refs.templeteTreeRef.store._getAllNodes().length;i++){
                this.$refs.templeteTreeRef.store._getAllNodes()[i].expanded=this.defaultExpand;
            }
        },
        setCheckedNodes() {                                     //模快权限的展开事件
            this.defaultExpand=true; //展开所有节点
            for(var i=0;i<this.$refs.templeteTreeRef.store._getAllNodes().length;i++){
                this.$refs.templeteTreeRef.store._getAllNodes()[i].expanded=this.defaultExpand;
            }
        },
        getTempleteData(){                                      //获取所有模块权限的数据
            this.$http.get(this.$url + 'menu/selectObject').then(res => {
                if(res.data.code === 20001) {
                    this.templeteTreeData = res.data.data;
                    for(let item of res.data.data){
                        this.arr.push(item.id)
                    };
                    this.disabledFn(res.data.data);
                } else {
                    // this.$message.error(res.data.msg);
                }
            }).catch(err => {
                this.$message.error(err);
            })
        },
        getCheckTempleteData(){                                 //获取某个用户模块权限的数据
            let that = this;
            this.$http.get(this.$url + 'userManage/findUserMenu?userId=' + this.userId).then(res => {
                var userArrId = res.data.data;                  //后台返回的id组成的数组
                var userNewArr = [];
                var userItem = '';
                userArrId.forEach(item=>{
                     this.checked(item,this.templeteTreeData,userNewArr)
                })
                this.checkedKeys = userNewArr;
            }).catch(err => {
                // this.$message.error(err);
            })
        },
        checked(id,data,userNewArr){                            //去掉半选状态的id
            data.forEach(item => {
                if(item.id == id){
                    if(item.submenuList.length == 0){
                        userNewArr.push(item.id)
                    }
                }else{
                    if(item.submenuList.length != 0){
                        this.checked(id,item.submenuList,userNewArr)
                    }
                }
            });
        },
        saveTempleteData(){                                     //保存模块权限
            this.checkedId = this.$refs.templeteTreeRef.getCheckedKeys();//选中的
            var parentArr = this.$refs.templeteTreeRef.getHalfCheckedKeys();//半选的
            var templeteArrId = this.checkedId.concat(parentArr);
            var type = {
                headers: {
                    'Content-type': 'application/json;charset=UTF-8'
                }
            }
            this.$http.post(this.$url + 'userManage/saveUserMenu?userId=' + this.userId + '&systemId=' + this.systemId,JSON.stringify(templeteArrId),type).then(res => {
                if(res.data.code == 20001) {
                    this.$store.dispatch('userManagementStore/getSearch', this.$url + 'userManage/search');
                    this.$message({message: '保存成功', type: 'success', duration: 2000});
                    this.halfCheckedId = [];
                    setTimeout(() => {
                        this.getTempleteData();
                        this.getCheckTempleteData();
                        let expandNodeId = this.$store.state.userManagementStore.expandNodeId;
                        this.$store.dispatch('userManagementStore/getEmployeeDataByDepartmentId', expandNodeId);			//刷新数据
                        this.$store.dispatch('userManagementStore/getSearch');
                    }, 500)
                }else{
                    this.$message({message: res.data.msg,type:'error'});
                }
            }).catch(err => {
                this.$message.error(err);
            })
        },
        disabledFn(arr) {                                       //禁用用户组管理
            if(arr.length > 0) {
                arr.forEach(item => {
                    if(item['name'] == '用户组管理') {
                        item['disabled'] = true;
                    }else if(item['name'] == '审批流程'){
                        item['disabled'] = true;
                    } else {
                        let submenuList = item['submenuList'];
                        if(submenuList && item['submenuList'].length > 0) {
                            this.disabledFn(item['submenuList']);
                        }
                    }
                })
            }
        },
    },
    mounted(){
        this.getTempleteData();
        this.getCheckTempleteData();
    }
    
}
</script>
<style>
    .templateO .el-scrollbar__wrap{overflow-x: auto !important;}
</style>
<style lang="less" scoped>
    .saveBtn{
        text-align: center;
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
    }
    .operatorBtn{
        padding: 9px 112px !important;
        margin-top: 10px;
    }
    .templateO {
        height: 100%;
        background-color: #fff;
        box-sizing: border-box;
        border-radius: 6px;
        width: 100%;
        .el-scrollbar__wrap{
            overflow-x: auto;
        }
        .templateO-title {
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
            font-size: 15px;
            margin-bottom: 10px;
            .templateO-btn{
                float: right;
                div{
                    display: inline-block;
                    margin-left: 10px;
                }
            }
        }
        .templateO-li{
            font-size: 14px;
            font-weight: normal;
            font-stretch: normal;
            letter-spacing: 1px;
            color: #797979;
            height: calc(100% - 10px) !important;
            overflow-y: auto;
            li{
                margin-bottom: 5px;
            }
        }
    }
</style>
